package joseph;

//约瑟夫环形列表
public class CircleSingleLinkedList {
    Boy first=new Boy(-1);
    public static void main(String[] args) {
        CircleSingleLinkedList linkedList = new CircleSingleLinkedList();
        linkedList.addBoyByNum(20);
        System.out.println(linkedList.getSize());
        //linkedList.list();
        linkedList.countBoy(1,2);
    }

    /*
    * @params: 小孩数量
    *
    */
    public void addBoyByNum(int nums){
        if (nums<1){
            System.out.println("num值不正确");
            return;
        }
        Boy cur = null;
        for (int i = 1; i <= nums; i++) {
            Boy boy = new Boy(i);
            if (i==1){
                first=boy;
                first.setNext(first);
                cur=first;
            }else{
                cur.setNext(boy);
                boy.setNext(first);
                cur=boy;
            }
        }
    }

    public void list(){
        if (first.getNo()==-1){
            System.out.println("链表为空");
            return;
        }
        Boy cur =first;
        do{
            System.out.println(cur);
            cur=cur.getNext();
        }while (cur!=first);
    }

    /*
     *  约瑟夫出圈题
     *  @Params startNo 从谁开始
     *          countNum 每次数几个人
     */
    public void countBoy(int startNo,int countNum){
        if (first==null||startNo<1||startNo>getSize()){
            System.out.println("参数输入有误");
            return;
        }
        Boy temp=null;
        if (startNo>1){
            for (int i = 1; i <startNo-1 ; i++) {
                first=first.getNext();
            }
            temp=first;
            first=first.getNext();
        }else {
            temp=first;
            for (int i = 0; i < getSize()-1; i++) {
                temp=temp.getNext();
            }
        }
        while (temp!=first){
            // 计算自己的一次,只需要移动count-1次
            for (int i = 1; i < countNum; i++) {
                first=first.getNext();
                temp=temp.getNext();
            }
            System.out.println(first+"出圈");
            first = first.getNext();
            temp.setNext(first);
        }
        System.out.println(temp+"最后留在圈内");
    }

    public int getSize(){
        if (first==null){
            return 0;
        }
        Boy temp=first;
        int count=1;
        while (true){
            if (temp.getNext()==first){
                return count;
            }
            temp=temp.getNext();
            count++;
        }
    }


}
class Boy{
    private int no;
    private Boy next;

    public Boy(int no) {
        this.no = no;
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public Boy getNext() {
        return next;
    }

    public void setNext(Boy next) {
        this.next = next;
    }

    @Override
    public String toString() {
        return "Boy{" +
                "no=" + no+
                '}';
    }
}
